package com.csun.cmny.security.core.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-10-22 18:08
 * @Description:
 */
@Component
public class HuaLongAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler pcAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler pcAuthenticationFailureHandler;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    /**
     * Configure.
     *
     * @param http the http
     */
    @Override
    public void configure(HttpSecurity http) {

        HuaLongAuthenticationFilter huaLongAuthenticationFilter = new HuaLongAuthenticationFilter();
        huaLongAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        huaLongAuthenticationFilter.setAuthenticationSuccessHandler(pcAuthenticationSuccessHandler);
        huaLongAuthenticationFilter.setAuthenticationFailureHandler(pcAuthenticationFailureHandler);
        String key = UUID.randomUUID().toString();
        huaLongAuthenticationFilter.setRememberMeServices(new PersistentTokenBasedRememberMeServices(key, userDetailsService, persistentTokenRepository));

        HuaLongAuthenticationProvider huaLongAuthenticationProvider = new HuaLongAuthenticationProvider();
        huaLongAuthenticationProvider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(huaLongAuthenticationProvider)
                .addFilterAfter(huaLongAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

//

    }
}
